package simi;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendPdfServlet extends HttpServlet {

	private static final String PDF_NAME = "simidev.pdf";	
	private String homeDirPrefix = SimiPropertyManager.getConfig().getString("files.home");

	public void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {

		String username = (String)req.getSession().getAttribute("username");
		String fileName = (String) req.getParameter("file");
		if (fileName == null || fileName.equals(""))
			fileName = PDF_NAME;
		// add the pdf suffix if it doesn't already exist
    		if (fileName.indexOf(".pdf") == -1)
      			fileName = fileName + ".pdf";

    		ServletOutputStream stream = null;
    		BufferedInputStream buf = null;
    		try {
      			stream = res.getOutputStream();
      			File pdf = new File(homeDirPrefix + username + "/" + fileName);
      			res.setContentType("application/pdf");

      			res.addHeader("Content-Disposition", "inline; filename="
          			+ fileName);
      			res.setContentLength((int) pdf.length());
      			FileInputStream input = new FileInputStream(pdf);
      			buf = new BufferedInputStream(input);
      			int readBytes = 0;

      			while ((readBytes = buf.read()) != -1)
        			stream.write(readBytes);
    		} catch (IOException ioe) {
      			throw new ServletException(ioe.getMessage());
    		} finally {
      			if (stream != null)
        				stream.close();
      			if (buf != null)
        			buf.close();
    		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException {
		doGet(req, res);
  	}
}

